<template>
  <basic-dialog
    width="60%"
    title="批量添加规格属性"
    :visible="visible"
    :showFooter="false"
    :handleClose="handleCanceled"
  >
    <el-checkbox v-model="isMustHave" @change="handleChangeMustHave">只展示必填项</el-checkbox>
    <BtnRender :render="renderBtnsBar" />
    <SkusTable
      :tableHeight="480"
      :dataSource="TableInfo.list"
      :columns="TableInfo.columns"
      :loading="TableInfo.loading"
      :selectionChange="TableInfo.setSelection"
    />
  </basic-dialog>
</template>
<script>
import BasicDialog from '@/components/BasicDialog';
import BtnRender from '@/components/JSXRender/BtnRender';
import SkusTable from '@/components/skusTable';
import { TableInfo } from '@/utils/getUtils';
import { getListPageBtnsBar } from '@/utils/getBtnsRender';
import { createExcelByExport, generateUuid, isResponseSuccess } from '@/utils/bizUtils';
import { TABLE_COLUMNS, EDIT_TABLE_COLUMNS } from './constants';
import { WHETHER_ENUMS } from '@/constants/commodity';
import {
  getSpecAndNotSpecAttributeVos,
  getTableListByFillAttributeValue,
  ATTR_VALUE_KEY,
  getUniqKey,
} from '../../utils';
import {
  getPotentialAttrInfoVoService,
  exportPotentialAttrInfoVoService,
  importPotentialAttrInfoVoUrl
} from '@/api/commodity/temporaryPurchasingGoods/latentProduct';
export default {
  components: {
    BasicDialog,
    BtnRender,
    SkusTable
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    valuesMaps: {
      type: Object,
      default: () => ({})
    },
    selection: {
      type: Array,
      default: () => []
    },
  },
  data () {
    return {
      isMustHave: false,
      TableInfo: new TableInfo(),
      sourceList: [],
      btnLoading: {
        export: false,
        submit: false
      }
    }
  },
  created () {
    this.updateTableColumns()
  },
  watch: {
    visible (val) {
      val && this.setTableList()
    }
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const btnList = [
        {
          label: '取消',
          method: this.handleCanceled,
          type: 'default'
        },
        {
          label: '导出模板',
          method: this.handleExportTemp,
          disabled: this.TableInfo.isNullList(),
          loading: this.btnLoading.export
        },
        {
          label: '导入模板',
          action: importPotentialAttrInfoVoUrl,
          methods: { handleUploadSuccess: this.handleUploadSuccess },
          isImport: true,
          loadingFn: this.TableInfo.setLoading
        },
        {
          label: '提交',
          method: this.handleSubmit,
          disabled: this.TableInfo.isNullList(),
          loading: this.btnLoading.submit
        },
      ]
      return getListPageBtnsBar(h, btnList)
    },
    // 取消
    handleCanceled () {
      this.isMustHave = false
      this.$emit('update:visible', false)
    },
    // 导出模板
    async handleExportTemp () {
      const uuid = generateUuid()
      const data = {
        uuid,
        exportPotentialAttrInfoDetailParams: this.TableInfo.list
      }
      const loadingFn = state => { this.btnLoading.export = state }
      const res = await exportPotentialAttrInfoVoService(data, loadingFn)
      createExcelByExport({ excelTitle: `批量添加规格属性_${uuid}`, res })
    },
    // 导入成功
    handleUploadSuccess (res) {
      if (!isResponseSuccess(res)) return
      const formatList = res?.retData.map(item => {
        const selectAttributeValueVos = item?.selectAttributeValueVos ?? []
        const attributeValueUuids = selectAttributeValueVos.map(item => item.attributeValueUuid)
        return { ...item, [ATTR_VALUE_KEY]: attributeValueUuids[0] }
      })
      this.TableInfo.setList(formatList)
      this.updateSourceList()
    },
    // 提交
    handleSubmit () {
      if (this.validateRequireItems()) return
      this.updateSourceList()
      const attributeVos = getSpecAndNotSpecAttributeVos(this.sourceList)
      const attributeVosGroups = _.groupBy(attributeVos, 'skuNo')
      this.$emit('update-spec-attrs', attributeVosGroups)
      this.handleCanceled()
    },
    // 变更是否只展示必填选择
    handleChangeMustHave (val) {
      this.updateSourceList()
      const updateList = val
        ? this.sourceList.filter(item => item.potentialAttributeMustHave == WHETHER_ENUMS.Yes)
        : this.sourceList
      this.TableInfo.setList(updateList)
    },
    // 校验必填
    validateRequireItems () {
      const checkSingle = () => {
        const hasSingle = this.TableInfo.list.length == 1
        const isNullVal = !this.TableInfo.list[0][ATTR_VALUE_KEY]
        return hasSingle && isNullVal
      }
      const checkMultiple = () => this.TableInfo.list.some(
        item => item.potentialAttributeMustHave == WHETHER_ENUMS.Yes && !item[ATTR_VALUE_KEY]
      )
      if (checkSingle()) return this.$message.warning('最少维护一个属性值')
      if (checkMultiple()) return this.$message.warning('必填属性值不能为空')
    },
    // 设置属性集合
    async setTableList () {
      const data = {
        isQuerySpec: true,
        getPotentialAttrInfoDetailParams: this.selection.map(item => ({
          skuNo: item.skuNo,
          categoryUuid: item.categoryUuid,
          recordDetailUuid: item.recordDetailUuid
        }))
      }
      const res = await getPotentialAttrInfoVoService(data, this.TableInfo.setLoading)
      const updateList = getTableListByFillAttributeValue(res?.retData, this.valuesMaps)
      this.TableInfo.setList(updateList)
      this.sourceList = updateList
    },

    // 更新表列
    updateTableColumns () {
      const updateColumns = [
        ...TABLE_COLUMNS,
        {
          title: '属性值',
          width: 200,
          render: (h, { row }) => (<el-input
            vModel_trim={row[ATTR_VALUE_KEY]}
            maxlength={30}
            show-word-limit={true}
          />)
        }
      ]
      this.TableInfo.setColumns(updateColumns)
    },
    // 更新源数据集合
    updateSourceList () {
      this.sourceList.forEach(item => {
        const target = this.TableInfo.list.find(row => getUniqKey(row) == getUniqKey(item))
        if (target && target[ATTR_VALUE_KEY]) {
          item[ATTR_VALUE_KEY] = target[ATTR_VALUE_KEY]
        }
      })
    },
  }
}
</script>
